"""
视频服务层 - 处理视频相关的业务逻辑
"""
from typing import Dict, Any, Optional, List
from ..utils import logger
from backend.sdk.script_file import Script_file


class VideoConfigProcessor:
    """视频配置处理器"""

    @staticmethod
    def process(script: Script_file, video_conf: Dict[str, Any]) -> Script_file:
        """处理视频配置，支持单个或多个视频素材"""
        try:
            logger.info("🎬 开始处理视频配置")

            # 支持两种格式：单个视频配置和多个视频配置
            video_materials = VideoConfigProcessor._parse_video_materials(
                video_conf)

            if not video_materials:
                logger.warning("未检测到有效的视频素材配置")
                return script

            # 处理每个视频素材
            for index, video_material_config in enumerate(video_materials):
                VideoConfigProcessor._process_single_video(
                    script, video_material_config, index)

            logger.info(f"✅ 成功处理了 {len(video_materials)} 个视频素材")
            return script

        except Exception as e:
            logger.error(f"处理视频配置失败: {e}")
            raise

    # 将单个或者多个视频素材转换为脚本片段

    @staticmethod
    def _parse_video_materials(video_conf: Dict[str, Any]) -> List[Dict[str, Any]]:
        """解析视频素材配置，支持单个和多个视频格式"""
        video_materials = []

        # 格式1：单个视频素材（兼容现有格式）
        if 'background_material' in video_conf:
            # 解析基础参数
            basic_params = VideoConfigProcessor._parse_basic_params(video_conf)

            video_material_config = {
                'material_config': video_conf['background_material'],
                'start_time': basic_params['start_time'],
                'duration': basic_params['duration'],
                'track_name': video_conf.get('track_name', '背景轨道'),
                'relative_index': video_conf.get('relative_index', 0)
            }
            video_materials.append(video_material_config)

        # 格式2：多个视频素材
        if 'video_materials' in video_conf:
            for material_config in video_conf['video_materials']:
                video_material_config = {
                    'material_config': material_config.get('material', {}),
                    'start_time': material_config.get('start_time', 0),
                    'duration': material_config.get('duration', 3000000),
                    'track_name': material_config.get('track_name', f'视频轨道_{len(video_materials) + 1}'),
                    'relative_index': material_config.get('relative_index', len(video_materials))
                }
                video_materials.append(video_material_config)

        return video_materials

    @staticmethod
    def _process_single_video(script: Script_file, video_config: Dict[str, Any], index: int) -> None:
        """处理单个视频素材"""
        try:
            # 解析视频素材
            background_material = VideoConfigProcessor.parse_background_material(
                video_config['material_config']
            )

            if background_material:
                # 确保轨道名称唯一
                track_name = video_config['track_name']
                if index > 0:
                    track_name = f"{track_name}_{index + 1}"

                # 添加视频轨道
                VideoConfigProcessor.add_video_track(
                    script,
                    background_material,
                    video_config['start_time'],
                    video_config['duration'],
                    track_name,
                    video_config['relative_index']
                )

                logger.info(f"✅ 成功处理视频素材: {background_material.material_name}")
            else:
                logger.warning(f"第 {index + 1} 个视频素材解析失败")

        except Exception as e:
            logger.error(f"处理第 {index + 1} 个视频素材失败: {e}")
            raise

    @staticmethod
    def _parse_basic_params(video_conf: Dict[str, Any]) -> Dict[str, Any]:
        """解析基础参数"""
        return {
            'start_time': video_conf.get('start_time', 0),
            'duration': video_conf.get('duration', 3000000)  # 默认3秒
        }

    @staticmethod
    def add_video_track(script: Script_file, video_material, start_time: int, duration: int,
                        track_name: str = "视频轨道", relative_index: int = 0):
        """添加视频轨道"""
        try:
            from sdk.video_segment import Video_segment
            from sdk.time_util import Timerange
            from sdk.track import Track_type

            # 创建时间范围
            video_timerange = Timerange(start_time, duration)

            # 创建视频片段
            video_segment = Video_segment(
                material=video_material,
                target_timerange=video_timerange
            )

            # 添加轨道（使用相对索引控制层级）
            script.add_track(Track_type.video, track_name,
                             relative_index=relative_index)

            # 添加片段到轨道
            script.add_segment(video_segment, track_name)

            logger.info(f"✅ 成功添加视频轨道: {track_name} (层级: {relative_index})")

        except Exception as e:
            logger.error(f"添加视频轨道失败: {e}")
            raise

    @staticmethod
    def add_background_track(script: Script_file, background_material, start_time: int, duration: int):
        """添加背景视频轨道（兼容性方法）"""
        VideoConfigProcessor.add_video_track(
            script, background_material, start_time, duration, "背景轨道", 0
        )

    @staticmethod
    def parse_background_material(background_material_data: Dict[str, Any]) -> Optional[Any]:
        """解析背景素材"""
        from sdk.local_materials import Video_material, Crop_settings

        if not background_material_data:
            return None

        try:
            material_path = background_material_data.get('path')
            if not material_path:
                logger.warning("视频素材路径为空")
                return None

            material_name = background_material_data.get('name', '视频素材')
            crop_data: Dict[str, Any] = background_material_data.get(
                'crop_settings', {})

            # 创建裁剪设置
            crop_settings = Crop_settings(
                upper_left_x=crop_data.get('upper_left_x', 0.0),
                upper_left_y=crop_data.get('upper_left_y', 0.0),
                upper_right_x=crop_data.get('upper_right_x', 1.0),
                upper_right_y=crop_data.get('upper_right_y', 0.0),
                lower_left_x=crop_data.get('lower_left_x', 0.0),
                lower_left_y=crop_data.get('lower_left_y', 1.0),
                lower_right_x=crop_data.get('lower_right_x', 1.0),
                lower_right_y=crop_data.get('lower_right_y', 1.0)
            )

            # 创建视频素材
            video_material = Video_material(
                path=material_path,
                material_name=material_name,
                crop_settings=crop_settings
            )

            logger.info(f"✅ 成功创建视频素材: {video_material.material_name}")
            return video_material

        except Exception as e:
            logger.error(f"创建视频素材失败: {e}")
            raise

    @staticmethod
    def build_video_response_info(video_conf: Dict[str, Any]) -> Dict[str, Any]:
        """构建视频配置的响应信息"""
        response_info = {
            "total_videos": 0,
            "video_tracks": []
        }

        # 处理单个视频格式
        if 'background_material' in video_conf:
            basic_params = VideoConfigProcessor._parse_basic_params(video_conf)
            track_info = {
                "track_name": video_conf.get('track_name', '背景轨道'),
                "material_name": video_conf['background_material'].get('name', '背景素材'),
                "material_path": video_conf['background_material'].get('path', ''),
                "start_time": basic_params['start_time'],
                "duration": basic_params['duration'],
                "relative_index": video_conf.get('relative_index', 0)
            }
            response_info["video_tracks"].append(track_info)
            response_info["total_videos"] = 1

        # 处理多个视频格式
        if 'video_materials' in video_conf:
            for index, material_config in enumerate(video_conf['video_materials']):
                track_info = {
                    "track_name": material_config.get('track_name', f'视频轨道_{index + 1}'),
                    "material_name": material_config.get('material', {}).get('name', f'视频素材_{index + 1}'),
                    "material_path": material_config.get('material', {}).get('path', ''),
                    "start_time": material_config.get('start_time', 0),
                    "duration": material_config.get('duration', 3000000),
                    "relative_index": material_config.get('relative_index', index)
                }
                response_info["video_tracks"].append(track_info)

            response_info["total_videos"] = len(video_conf['video_materials'])

        return response_info
